import { _decorator, find, Layout, Node, Sprite, SpriteFrame } from 'cc';
import BaseView from '../../../../../../extensions/app/assets/base/BaseView';
import { IMiniViewNames } from '../../../../../app-builtin/app-admin/executor';
import { ListView } from 'db://pkg/@colayue/cc-comp-list-view';
import { BodyPartType, MainPageTabBtn, MainPageTabBtnData } from './MainPageTabBtn';
import { MainPageViewItem, MainPageViewItemData } from './MainPageViewItem';
import { app } from 'db://assets/app/app';


const { ccclass, property } = _decorator;
@ccclass('PageMainpage')
export class PageMainpage extends BaseView {
    // 子界面列表，数组顺序为子界面排列顺序
    protected miniViews: IMiniViewNames = [];

    //#region 节点
    @property(Layout)
    /**
     * 角色容器
     */
    private role_container: Layout;

    @property(Sprite)
    /**
     * 人物 身体
     */
    private body: Sprite;

    @property(Sprite)
    /**
     * 人物 衣服
     */
    private clothes: Sprite;

    @property(Sprite)
    /**
     * 人物 头发
     */
    private hair: Sprite;

    @property(Sprite)
    /**
     * 人物 眼睛
     */
    private eyes: Sprite;

    @property(Sprite)
    /**
     * 人物 丝袜
     */
    private stockings: Sprite;

    @property(Sprite)
    /**
     * 人物 鞋子
     */
    private shoes: Sprite;

    @property(ListView)
    /**
     * tab view
     */
    private tab_view: ListView

    /**
     * 显示的部位数据
     */
    private part_datas: MainPageTabBtnData[]

    /**
     * 默认人物形象ID
     */
    private default_show_Ids: Map<BodyPartType,number>=new Map();

    @property(ListView)
    /**
     * item view
     */
    private item_view: ListView


    /**
     * 显示的部位数据
     */
    private single_part_datas: Record<BodyPartType, MainPageViewItemData[]>
    //#endregion

    protected async beforeShow(next: (error?: string) => void, data?: any) {
        app.lib.logger.log("【PageMainpage】 输出===>>>beforeShow step 1")
         //初始化数据
        await this.initDatas()

        //初始化默认形象
        this.default_show_Ids.set(BodyPartType.clothes,1)
        this.default_show_Ids.set(BodyPartType.eyes,1)
        this.default_show_Ids.set(BodyPartType.hair,1)
        this.default_show_Ids.set(BodyPartType.shoes,1)
        this.default_show_Ids.set(BodyPartType.stockings,1)

        app.lib.logger.log("【PageMainpage】 输出===>>>beforeShow step 2")
        next();
    }

    // 初始化的相关逻辑写在这
    onLoad() {
        //初始化 UI
        this.initBaseRole();
        this.initTabView();
        this.initItemView();

        app.lib.logger.log("【PageMainpage】 输出===>>>onLoad")
    }

    /**
     * 初始化数据
     */
    private async  initDatas(): Promise<void> {
        this.part_datas = []
        this.part_datas.push({ part: BodyPartType.clothes, isSelect: true, isNew: false })
        this.part_datas.push({ part: BodyPartType.eyes, isSelect: false, isNew: false })
        this.part_datas.push({ part: BodyPartType.hair, isSelect: false, isNew: false })
        this.part_datas.push({ part: BodyPartType.shoes, isSelect: false, isNew: false })
        this.part_datas.push({ part: BodyPartType.stockings, isSelect: false, isNew: true })

        this.single_part_datas = {} as Record<BodyPartType, MainPageViewItemData[]>;

        const list = await app.manager.tables.GetPartDatas();

        list.forEach((innerMap, outerKey) => {
            innerMap.forEach((partData, innerKey) => {    
                let part_type = outerKey as BodyPartType;
                const bid = innerKey;
                this.pushPartData(part_type, { part_type: part_type, icon_id: bid, select_status: false, video_status: false, new_status: false } as MainPageViewItemData)
            });
        });
    }

    /**
     * 添加数据
     * @param part 
     * @param data 
     */
    private pushPartData(part: BodyPartType, data: MainPageViewItemData): void {
        if (!this.single_part_datas[part]) {
            this.single_part_datas[part] = []
        }

        this.single_part_datas[part].push(data);
    }

    //#region  形象
    /**
     * 初始化基础角色
     */
    private initBaseRole(): void {
        app.lib.logger.log("【PageMain】输出 ===>>> initBaseRole")

        this.updateRoleShow()
    }

    /**
     * 更新基础角色形象
     */
    private updateRoleShow(): void {
        this._updateClothes(this.default_show_Ids.get(BodyPartType.clothes));
        this._updateHair(this.default_show_Ids.get(BodyPartType.hair));
        this._updateEyes(this.default_show_Ids.get(BodyPartType.eyes));
        this._updateShoes(this.default_show_Ids.get(BodyPartType.shoes));
        this._updateStockings(this.default_show_Ids.get(BodyPartType.stockings));
    }

    /**
     * 更新 Clothes
     * @param show_id 
     */
    private async _updateClothes(show_id: number): Promise<void> {
        let clothes_res_path = `sprites/part/clothes/clothes_${show_id}/spriteFrame`

        app.manager.loader.load({
            path: clothes_res_path, bundle: 'res-native', type: SpriteFrame, onComplete: (spriteFrame) => {
                this.clothes.spriteFrame = spriteFrame
            }
        })
    }

    /**
     * 更新 Hair
     * @param show_id 
     */
    private async _updateHair(show_id: number): Promise<void> {
        let hair_res_path = `sprites/part/hair/hair_${show_id}/spriteFrame`
        app.manager.loader.load({
            path: hair_res_path, bundle: 'res-native', type: SpriteFrame, onComplete: (spriteFrame) => {
                this.hair.spriteFrame = spriteFrame
            }
        })
    }

    /**
     * 更新 Eye
     * @param show_id 
     */
    private async _updateEyes(show_id: number): Promise<void> {
        let eyes_res_path = `sprites/part/eyes/eyes_${show_id}/spriteFrame`
        app.manager.loader.load({
            path: eyes_res_path, bundle: 'res-native', type: SpriteFrame, onComplete: (spriteFrame) => {
                this.eyes.spriteFrame = spriteFrame
            }
        })
    }

    /**
     * 更新 Stockings
     * @param show_id 
     */
    private async _updateStockings(show_id: number): Promise<void> {
        let stockings_res_path = `sprites/part/stockings/stockings_${show_id}/spriteFrame`
        app.manager.loader.load({
            path: stockings_res_path, bundle: 'res-native', type: SpriteFrame, onComplete: (spriteFrame) => {
                this.stockings.spriteFrame = spriteFrame
            }
        })
    }

    /**
     * 更新 Shoes
     * @param show_id 
     */
    private async _updateShoes(show_id: number): Promise<void> {
        let shoes_res_path = `sprites/part/shoes/shoes_${show_id}/spriteFrame`
        app.manager.loader.load({
            path: shoes_res_path, bundle: 'res-native', type: SpriteFrame, onComplete: (spriteFrame) => {
                this.shoes.spriteFrame = spriteFrame
            }
        })
    }

    //#endregion


    /**
     * 初始化tab  列表
     */
    private initTabView(): void {
        app.lib.logger.log("【PageMain】输出 ===>>> initTabView")
        // this.tab_view.node.on('create-item', (item: Node) => {
        //     let ele = item.getComponent(MainPageTabBtn);
        //     ele?.addCallBack(this.onClickItemFunc)
        // });
        this.tab_view.node.on('update-item', (item: Node, index: number) => {
            let ele = item.getComponent(MainPageTabBtn);
            let data = this.part_datas[index]
            ele?.setData(data);
            ele?.addCallBack(this.onClickPartTabBtn.bind(this))
        });
        this.tab_view.count = this.part_datas.length
    }


    /**
     * 点击tab按钮
     * @param part_type 
     */
    private onClickPartTabBtn(part_type: BodyPartType): void {
        this.initItemView(part_type);
    }


    /**
     * 初始化 item 列表
     * @param part 
     */
    private initItemView(part: BodyPartType = BodyPartType.clothes): void {
        let list_data = this.single_part_datas[part] as MainPageViewItemData[]
        app.lib.logger.log("【PageMainpage】输出 ===>>> initItemView:", list_data.length)

        this.item_view.node.on('create-item', (item: Node) => {
            app.lib.logger.log("PageMainpage】输出 ===>>> create-item")
            let ele = item.getComponent(MainPageViewItem);
            ele?.addCallBack(this.onClickItemFunc)
        });
        this.item_view.node.on('update-item', (item: Node, index: number) => {
            let ele = item.getComponent(MainPageViewItem);
            let data = list_data[index]
            ele?.setData(data);
            ele?.addCallBack(this.onClickItemFunc.bind(this))
        });
        this.item_view.count = list_data.length
    }

    /**
     * 点击icon item
     * @param icon_id 
     * @param part_type 
     */
    private onClickItemFunc(icon_id: number, part_type: BodyPartType): void {
        let func = (icon_id: number) => {
            //改变形象 
            switch (part_type) {
                case BodyPartType.clothes:
                    this._updateClothes(icon_id)
                    break;
                case BodyPartType.eyes:
                    this._updateEyes(icon_id)
                    break;
                case BodyPartType.hair:
                    this._updateHair(icon_id)
                    break;
                case BodyPartType.shoes:
                    this._updateShoes(icon_id)
                    break;
                case BodyPartType.stockings:
                    this._updateStockings(icon_id)
                    break;
                default:
                    break;
            }
        }

        this.default_show_Ids.set(part_type,icon_id)
        func(icon_id);
    }

    // 界面打开时的相关逻辑写在这(onShow可被多次调用-它与onHide不成对)
    onShow(params: any) { this.showMiniViews({ views: this.miniViews }); }

    // 界面关闭时的相关逻辑写在这(已经关闭的界面不会触发onHide)
    onHide(result: undefined) {
        // app.manager.ui.show<PageMainpage>({name: 'PageMainpage', onHide:(result) => { 接收到return的数据，并且有类型提示 }})
        return result;
    }
}